package com.dhu.stylefit.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dhu.stylefit.Response;
import com.dhu.stylefit.model.VrTry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/vr-tryon")
public class VrTryOnController {
    // 阿里云OSS配置
    private static final String ENDPOINT = "oss-cn-shanghai.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tESEndX3dz6Y5pvxDE8";
    private static final String ACCESS_KEY_SECRET = "RABbDoW9gNKc8dBE51yBBAxWrf9KI9";
    private static final String BUCKET_NAME = "shenhuixaioliweb1";
    private static final Logger logger = LoggerFactory.getLogger(VrTryOnController.class);

    @PostMapping("/try-on")
    public Response<String> tryOn(
            @RequestParam("personImage") MultipartFile personImage,
            @RequestParam(value = "topGarment", required = false) MultipartFile topGarment,
            @RequestParam(value = "bottomGarment", required = false) MultipartFile bottomGarment) {

        // 1. 参数校验
        if (personImage == null || personImage.isEmpty()) {
            return Response.newFail("模特图片不能为空");
        }

        long maxFileSize = 5 * 1024 * 1024; // 5MB
        if (personImage.getSize() > maxFileSize ||
                (topGarment != null && topGarment.getSize() > maxFileSize) ||
                (bottomGarment != null && bottomGarment.getSize() > maxFileSize)) {
            return Response.newFail("图片大小不能超过5MB");
        }

        // 2. 上传图片到OSS
        String personImageUrl;
        String topGarmentUrl = null;
        String bottomGarmentUrl = null;

        try {
            personImageUrl = saveFileToOSS(personImage);
            logger.info("模特图上传成功: {}", personImageUrl);

            if (topGarment != null && !topGarment.isEmpty()) {
                topGarmentUrl = saveFileToOSS(topGarment);
                logger.info("上衣服装上传成功: {}", topGarmentUrl);
            }

            if (bottomGarment != null && !bottomGarment.isEmpty()) {
                bottomGarmentUrl = saveFileToOSS(bottomGarment);
                logger.info("下衣服装上传成功: {}", bottomGarmentUrl);
            }

            // 3. 调用虚拟试衣服务
            String imageUrl = VrTry.executePythonScript(personImageUrl, topGarmentUrl, bottomGarmentUrl);

            if (imageUrl != null) {
                return Response.newSuccess(imageUrl);
            } else {
                return Response.newFail("试穿任务提交失败");
            }

        } catch (IOException e) {
            logger.error("图片上传失败", e);
            return Response.newFail("图片上传失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("虚拟试衣服务异常", e);
            return Response.newFail("系统异常: " + e.getMessage());
        }
    }

    private String saveFileToOSS(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try (InputStream inputStream = file.getInputStream()) {
            ossClient.putObject(new PutObjectRequest(BUCKET_NAME, uniqueFileName, inputStream));
            return "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + uniqueFileName;
        } finally {
            ossClient.shutdown();
        }
    }
}
